package com.tian.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * {@code @description:} token生成和校验
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/1/26 20:59
 * {@code @version:} 1.0
 */
@Slf4j
public class JwtGeneratorUtil {

    private static String SECRET_KEY = "CHARGE-STATION";

    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] keySecretByte = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        return new SecretKeySpec(keySecretByte, signatureAlgorithm.getJcaName());
    }

    /**
     * shengcheng jwt token
     */
    public static String generatorToken(Map<String, Object> payLoad) {
        ObjectMapper objectMapper = new ObjectMapper();
        String token = null;
        try {
            token = Jwts.builder().setPayload(objectMapper.writeValueAsString(payLoad)).
                    signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
        } catch (JsonProcessingException e) {
            log.error("generatorToken :" + e);
        }
        return token;
    }

    /**
     * 根据token解析出token中的内容
     */
    public static Claims parseToken(String token) {
        Jws<Claims> claimsJwt = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        return claimsJwt.getBody();
    }

    public static void main(String[] args) {
        String s = DigestUtils.md5DigestAsHex("123456".getBytes());
        System.out.println(s);
    }
}
